﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThinhTien.EF4;
using ThinhTien.Models;
using DevExpress.Web.Mvc;
using DevExpress.Data;
using DevExpress.Data.Filtering;
using DevExpress.Data.Linq;
using DevExpress.Data.Linq.Helpers;

namespace ThinhTien.Data.Repository
{
    public class SlideRepository : BaseRepository<SlideRepository>
    {
        public void AddNew(SlideViewModel model)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    Guid? imageID = null;

                    if (model.Photo != null)
                    {
                        imageID = Guid.NewGuid();

                        db.Images.Add(new Image
                        {
                            ID = imageID.Value,
                            Size = model.Photo.Length,
                            Image1 = model.Photo,
                            Filename = model.Title
                        });
                    }

                    db.Slides.Add(new Slide()
                    {
                        ID = Guid.NewGuid(),
                        ImageID = imageID,
                        Link = model.Link,
                        LookupID = model.LookupID,
                        Title = model.Title,
                        CreatedBy = model.UserID,
                        UpdatedBy = model.UserID,
                        CreatedDate = DateTime.Now,
                        UpdatedDate = DateTime.Now

                    });

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }

        public void Update(SlideViewModel model)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    var slide = (from item in db.Slides
                                 where item.ID == model.ID
                                 select item).FirstOrDefault();

                    if (slide != null)
                    {
                        slide.Link = model.Link;
                        slide.Title = model.Title;
                        slide.LookupID = model.LookupID;
                        slide.UpdatedBy = model.UserID;
                        slide.UpdatedDate = DateTime.Now;

                        if (model.Photo != null)
                        {
                            var image = (from item in db.Images
                                         where item.ID == slide.ImageID
                                         select item).FirstOrDefault();

                            if (image != null)
                            {
                                image.Image1 = model.Photo;
                            }
                            else
                            {
                                Guid imageID = Guid.NewGuid();

                                db.Images.Add(new Image
                                {
                                    ID = imageID,
                                    Size = model.Photo.Length,
                                    Image1 = model.Photo,
                                    Filename = model.Title
                                });

                                slide.ImageID = imageID;
                            }
                        }

                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }

        public void Delete(List<Guid> ids)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    var slides = (from item in db.Slides
                                  where ids.Contains(item.ID)
                                  select item).ToList();

                    foreach (var slide in slides)
                    {
                        db.Slides.Remove(slide);
                    }

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                throw ex;
            }
        }

        public SlideViewModel GetSlideDetail(Guid slideID)
        {
            var slide = (from item in Database.DbInstant.Slides
                         join image in Database.DbInstant.Images on item.ImageID equals image.ID into left_join
                         where item.ID == slideID
                         from t in left_join.DefaultIfEmpty()
                         select new SlideViewModel()
                         {
                             ID = item.ID,
                             Link = item.Link,
                             Title = item.Title,
                             LookupID = item.LookupID,
                             Photo = t.Image1
                         }).FirstOrDefault();

            return slide;
        }

        public KeyValuePair<Guid, string>[] GetTypes(string type)
        {
            using (var db = new THINHTIENDBEntities())
            {
                var query = (from item in db.Lookups
                             where item.FunctionName == type
                             select item).ToList();


            }
            var results = new List<KeyValuePair<Guid, string>>();

            results.Add(new KeyValuePair<Guid, string>(Guid.NewGuid(), "1"));
            results.Add(new KeyValuePair<Guid, string>(Guid.NewGuid(), "2"));
            results.Add(new KeyValuePair<Guid, string>(Guid.NewGuid(), "3"));

            return results.ToArray();
        }
    }

    public static class SlideBindingHandler
    {
        public static void GetDataRowCount(GridViewCustomBindingGetDataRowCountArgs e)
        {
            using (var db = new THINHTIENDBEntities())
            {
                e.DataRowCount = (from slide in db.Slides
                                  select slide).ApplyFilter(e.FilterExpression).Count();
            }
        }

        public static void GetData(GridViewCustomBindingGetDataArgs e)
        {
            using (var db = new THINHTIENDBEntities())
            {
                var query = (from item in db.Slides
                             join user in db.Users on item.UpdatedBy equals user.ID
                             join lookup in db.Lookups on item.LookupID equals lookup.ID
                             select new
                             {
                                 item.ID,
                                 item.ImageID,
                                 item.Link,
                                 item.Title,
                                 item.LookupID,
                                 item.UpdatedBy,
                                 item.UpdatedDate,
                                 item.CreatedBy,
                                 item.CreatedDate,
                                 user.UserName,
                                 lookup.Name
                             }).Distinct().OrderByDescending(p => p.UpdatedDate)
                            .ApplySorting(e.State.SortedColumns)
                            .ApplyFilter(e.State.FilterExpression)
                            .Skip(e.StartDataRowIndex).Take(e.DataRowCount);

                List<SlideViewModel> data = new List<SlideViewModel>();
                foreach (dynamic item in query)
                {
                    data.Add(new SlideViewModel()
                    {
                        ID = item.ID,
                        Link = item.Link,
                        Title = item.Title,
                        LookupName = item.Name,
                        UpdatedBy = item.UserName,
                        UpdatedDate = item.UpdatedDate
                    });
                }

                if (data.Count == 0)
                {
                    data.Add(new SlideViewModel()
                    {
                        ID = Guid.NewGuid()
                    });
                }

                e.Data = data;
            }
        }
    }
}
